<script lang="ts">
    import {
        create_node,
        update_node_content,
    } from "$lib/api/board/board_draw";
    import { get_user_session } from "$lib/api/user";
    import { request } from "$lib/utils/request";
    import type { XYPosition } from "@xyflow/svelte";
    import { drawStore } from "../store.svelte";
    import { Modal } from "@skeletonlabs/skeleton-svelte";
    import { X } from "lucide-svelte";
    import type { BasicLinkContent } from "$lib/api/board/board_draw_type";

    interface ModalProps {
        nodeId?: string;
        content?: BasicLinkContent;
        width?: number;
        height?: number;
        position?: XYPosition;
        onClose: () => void;
    }

    let props: ModalProps = $props();

    let linkName = $state(props.content?.link_name ?? "");
    let linkUrl = $state(props.content?.link_url ?? "");

    const valid = $derived(
        linkName != "" &&
            (linkUrl.startsWith("http://") || linkUrl.startsWith("https://")),
    );

    async function createNode() {
        if (
            props.width == undefined ||
            props.height == undefined ||
            props.position == undefined
        ) {
            return;
        }
        const sessionId = await get_user_session();
        await request(
            create_node({
                session_id: sessionId,
                board_id: drawStore.boardInfo?.board_id ?? "",
                draw_id: drawStore.drawId,
                x: props.position.x,
                y: props.position.y,
                w: props.width,
                h: props.height,
                content: {
                    BasicLinkContent: {
                        link_name: linkName,
                        link_url: linkUrl,
                    },
                },
                node_style: {
                    bg_color: "bg-surface-200",
                    border_width: "border-2",
                    border_color: "border-surface-300",
                    font_color: "text-surface-800",
                    layer: 0,
                },
            }),
        );
        props.onClose();
    }

    async function updateNode() {
        if (props.nodeId == undefined) {
            return;
        }
        const sessionId = await get_user_session();
        await request(
            update_node_content({
                session_id: sessionId,
                board_id: drawStore.boardInfo?.board_id ?? "",
                draw_id: drawStore.drawId,
                node_id: props.nodeId,
                content: {
                    BasicLinkContent: {
                        link_name: linkName,
                        link_url: linkUrl,
                    },
                },
            }),
        );
        props.onClose();
    }
</script>

<Modal
    open={true}
    triggerBase="btn preset-tonal"
    contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl shadow-surface-500 w-[600px]"
    backdropBase="backdrop-none"
    closeOnEscape={false}
    closeOnInteractOutside={false}
    onOpenChange={(ev) => {
        if (!ev.open) {
            props.onClose();
        }
    }}
>
    {#snippet content()}
        <header class="flex justify-between">
            <h4 class="h4">创建链接节点</h4>
            <button
                type="button"
                class="btn preset-ghost-primary-500"
                onclick={() => props.onClose()}
            >
                <X />
            </button>
        </header>
        <main>
            <label class="label relative p-2">
                <span class="label-text">链接名称</span>
                <input
                    class="input rounded-none bg-surface-100-900 text-surface-900-100"
                    type="text"
                    placeholder="请输入链接名称"
                    bind:value={linkName}
                />
            </label>
            <label class="label relative p-2">
                <span class="label-text">链接地址</span>
                <input
                    class="input rounded-none bg-surface-100-900 text-surface-900-100"
                    type="text"
                    placeholder="请输入链接地址"
                    bind:value={linkUrl}
                />
                {#if !(linkUrl.startsWith("http://") || linkUrl.startsWith("https://"))}
                    <div class="text-error-400-600">
                        地址必须以http://或https://开头
                    </div>
                {/if}
            </label>
        </main>

        <footer class="flex justify-end gap-4">
            <button
                type="button"
                class="btn preset-tonal"
                onclick={() => props.onClose()}>取消</button
            >
            <button
                type="button"
                class="btn preset-filled-primary-900-100"
                disabled={!valid}
                onclick={() => {
                    if (props.nodeId == undefined) {
                        createNode();
                    } else {
                        updateNode();
                    }
                }}
            >
                确定
            </button>
        </footer>
    {/snippet}
</Modal>
